package com.onelap.bls.tc2.ui.calibration;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothProfile;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bls.blslib.base.BaseActivity;
import com.google.gson.Gson;
import com.onelap.bls.tc2.R;
import com.onelap.bls.tc2.ble.BleCallback;
import com.onelap.bls.tc2.ble.BleParams;
import com.onelap.bls.tc2.ble.BleUtil;
import com.onelap.bls.tc2.ui.index.DeviceBean;
import com.onelap.bls.tc2.util.HandleUtils;
import com.onelap.bls.tc2.view.TitleBar;

import java.io.UnsupportedEncodingException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.onelap.bls.tc2.ble.BleParams.StrUUID.BATTERY_LEVEL_UUID;
import static com.onelap.bls.tc2.ble.BleParams.StrUUID.TX_CHAR_UUID;
import static com.onelap.bls.tc2.ble.BleParams.StrUUID.VERSION_NAME_UUID;


@SuppressLint("SetTextI18n")
public class CalibrationActivity extends BaseActivity {

    @BindView(R.id.tb_title_bar)
    TitleBar tbTitleBar;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_electric)
    TextView tvElectric;
    @BindView(R.id.btn_wheel_diameters)
    Button btnWheelDiameters;
    @BindView(R.id.btn_slope)
    Button btnSlope;
    @BindView(R.id.btn_switch_to_ble)
    Button btnSwitchToBle;
    @BindView(R.id.ll_test_zero)
    LinearLayout llTestZero;
    @BindView(R.id.one_et_speed)
    EditText oneEtSpeed;
    @BindView(R.id.one_btn_confirm)
    Button oneBtnConfirm;
    @BindView(R.id.one_tv_show_1)
    TextView oneTvShow1;
    @BindView(R.id.one_tv_show_2)
    TextView oneTvShow2;
    @BindView(R.id.ll_test_one)
    LinearLayout llTestOne;
    @BindView(R.id.two_btn_start)
    Button twoBtnStart;
    @BindView(R.id.two_et_1)
    EditText twoEt1;
    @BindView(R.id.two_btn_1)
    Button twoBtn1;
    @BindView(R.id.two_iv_1)
    ImageView twoIv1;
    @BindView(R.id.two_et_2)
    EditText twoEt2;
    @BindView(R.id.two_btn_2)
    Button twoBtn2;
    @BindView(R.id.two_iv_2)
    ImageView twoIv2;
    @BindView(R.id.two_et_3)
    EditText twoEt3;
    @BindView(R.id.two_btn_3)
    Button twoBtn3;
    @BindView(R.id.two_iv_3)
    ImageView twoIv3;
    @BindView(R.id.two_btn_over)
    Button twoBtnOver;
    @BindView(R.id.two_tv_1)
    TextView twoTv1;
    @BindView(R.id.ll_test_two)
    LinearLayout llTestTwo;
    private BleUtil bleUtil;

    private int showPage = 0;  //0:选择  1：速度   2：坡度
    private DeviceBean deviceBean;


    @Override
    protected void initParams() {
        super.initParams();
        deviceBean = new Gson().fromJson(getIntent().getStringExtra("DeviceBean"), DeviceBean.class);
        bleUtil = new BleUtil(getActivity(), bleCallback);
        bleUtil.bindBleService();
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_calibration;
    }

    @Override
    protected void initFvb() {
        super.initFvb();
        ButterKnife.bind(this);
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        tbTitleBar.setTitle("跑步机校准");
        tbTitleBar.setBackgroundColor(Color.BLACK);
        tbTitleBar.setTitleColor(Color.WHITE);
        tbTitleBar.setLeftImageResource(R.mipmap.a2);
        tbTitleBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchShowPage(false, showPage);
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
    }

    @OnClick({
            R.id.btn_wheel_diameters, R.id.btn_slope, R.id.btn_switch_to_ble,
            R.id.one_btn_confirm, R.id.two_btn_start, R.id.two_btn_1,
            R.id.two_btn_2, R.id.two_btn_3, R.id.two_btn_over})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_wheel_diameters:
                tbTitleBar.setTitle("跑步机轮径校准");
                switchShowPage(true, 1);
                break;
            case R.id.btn_slope:
                tbTitleBar.setTitle("跑步机坡度校准");
                switchShowPage(true, 2);
                break;
            case R.id.btn_switch_to_ble:
                break;
            case R.id.one_btn_confirm:
                break;
            case R.id.two_btn_start:
                break;
            case R.id.two_btn_1:
                break;
            case R.id.two_btn_2:
                break;
            case R.id.two_btn_3:
                break;
            case R.id.two_btn_over:
                break;
        }
    }


    private BleCallback bleCallback = new BleCallback() {
        @Override
        public void bleHaveBlePermission(boolean isDoNext) {

        }

        @Override
        public void bleServiceConnected(ComponentName componentName, IBinder iBinder) {

        }

        @Override
        public void bleServiceDisConnected(ComponentName componentName) {

        }

        @Override
        public void bleServiceOnReceive(Context context, Intent intent) {

        }

        @Override
        public void bleBluetoothEnableState(boolean isSupport, boolean isEnable) {

        }

        @Override
        public void bleLeScanDevice(BluetoothDevice bluetoothDevice, int rssi, byte[] scanRecord, BleParams.ScanDeviceStateCode scanDeviceStateCode) {

        }

        @Override
        public void bleOnGattCallbackConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED)
                gatt.discoverServices();
        }

        @Override
        public void bleOnGattCallbackServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                bleUtil.disPlayCharacteristicsContent();
                bleUtil.setCharacteristicNotification(gatt);
            }
        }

        @Override
        public void bleOnGattCallbackCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            switch (characteristic.getUuid().toString().toLowerCase()) {
                case VERSION_NAME_UUID:
                    myHandler.sendMessage(Message.obtain(myHandler, 0, characteristic.getValue()));
                    break;
                case BATTERY_LEVEL_UUID:
                    myHandler.sendMessage(Message.obtain(myHandler, 1, characteristic.getValue()));
                    break;
                case TX_CHAR_UUID:
                    myHandler.sendMessage(Message.obtain(myHandler, 2, characteristic.getValue()));
                    break;
            }
        }

        @Override
        public void bleOnGattCallbackCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            switch (characteristic.getUuid().toString().toLowerCase()) {
                case VERSION_NAME_UUID:
                    myHandler.sendMessage(Message.obtain(myHandler, 0, characteristic.getValue()));
                    break;
                case BATTERY_LEVEL_UUID:
                    myHandler.sendMessage(Message.obtain(myHandler, 1, characteristic.getValue()));
                    break;
                case TX_CHAR_UUID:
                    myHandler.sendMessage(Message.obtain(myHandler, 2, characteristic.getValue()));
                    break;
            }
        }

        @Override
        public void bleOnGattCallbackCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            switch (characteristic.getUuid().toString().toLowerCase()) {
                case VERSION_NAME_UUID:
                    myHandler.sendMessage(Message.obtain(myHandler, 0, characteristic.getValue()));
                    break;
                case BATTERY_LEVEL_UUID:
                    myHandler.sendMessage(Message.obtain(myHandler, 1, characteristic.getValue()));
                    break;
                case TX_CHAR_UUID:
                    myHandler.sendMessage(Message.obtain(myHandler, 2, characteristic.getValue()));
                    break;
            }
        }
    };


    private MyHandler myHandler = new MyHandler(CalibrationActivity.this);

    private static class MyHandler extends HandleUtils<CalibrationActivity> {
        MyHandler(CalibrationActivity rootT) {
            super(rootT);
        }

        @Override
        public void handler0Event(CalibrationActivity object, Message msg) {
            super.handler0Event(object, msg);
            byte[] bytes = (byte[]) msg.obj;
            final StringBuilder value = new StringBuilder("");
            for (byte b : bytes) {
                value.append(String.valueOf(b));
            }
            object.tvVersion.setText("固件版本：" + String.valueOf(value));
        }

        @Override
        public void handler1Event(CalibrationActivity object, Message msg) {
            super.handler1Event(object, msg);
            byte[] bytes = (byte[]) msg.obj;
            try {
                String value = new String(bytes, "UTF-8");
                object.tvElectric.setText("剩余电量：" + value + "%");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void handler2Event(CalibrationActivity object, Message msg) {
            super.handler1Event(object, msg);
            byte[] bytes = (byte[]) msg.obj;
            String text = null;
            try {
                text = new String(bytes, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            LogUtils.i("ReceiveData", text);
            if (text == null) return;
            if (text.equals("88GG") || text.equals("80GG")) return;
            if (object.showPage == 1) {
                if (text.equals("88COM")) {
                    object.oneBtnConfirm.setEnabled(true);
                    ToastUtils.showShort("设备校准完成，可继续输入速度信息");
                } else {
                    if (text.startsWith("88")) {
                        String strRotationRate = text.substring(2);
                        if (strRotationRate.startsWith("0"))
                            strRotationRate.substring(1);
                        if (!strRotationRate.contains("."))
                            strRotationRate = strRotationRate + ".0";
                        object.oneTvShow1.setText(strRotationRate);
                    } else if (text.startsWith("89")) {
                        String strRotationRate = text.substring(2);
                        if (strRotationRate.startsWith("0"))
                            strRotationRate.substring(1);
                        object.oneTvShow2.setText(strRotationRate);
                    }
                }
            } else if (object.showPage == 2) {
                if (text.equals("80AA") || text.equals("80BB") || text.equals("80CC") || text.equals("80DD") || text.equals("80E")) {
                    switch (text) {
                        case "80AA":
                            ToastUtils.showShort("设备接收到开始指令");
                            object.twoBtn1.setEnabled(true);
                            break;
                        case "80BB":
                            ToastUtils.showShort("设备接收到坡度1指令");
                            object.twoBtn2.setEnabled(true);
                            break;
                        case "80CC":
                            ToastUtils.showShort("设备接收到坡度2指令");
                            object.twoBtn3.setEnabled(true);
                            break;
                        case "80DD":
                            ToastUtils.showShort("设备接收到坡度3指令");
                            object.twoBtnOver.setEnabled(true);
                            break;
                        case "80EE":
                            ToastUtils.showShort("设备接收到校准指令");
                            break;
                    }
                }
                String temp = text.substring(2);
                if (temp.startsWith("0")) temp.substring(1);
                object.twoTv1.setText(temp.concat("度"));
            }
        }

        @Override
        public void handler3Event(CalibrationActivity object, Message msg) {
            super.handler1Event(object, msg);

        }

        @Override
        public void handler4Event(CalibrationActivity object, Message msg) {
            super.handler4Event(object, msg);
        }
    }

    @Override
    protected void initOnPause() {
        super.initOnPause();
    }

    @Override
    public void onBackPressed() {
        switchShowPage(false, showPage);
    }

    /**
     * 切换页面
     *
     * @param isInto 进入或退出
     * @param flag   页面标记
     */
    private void switchShowPage(boolean isInto, int flag) {
        showPage = flag;
        if (isInto) {
            llTestZero.setVisibility(flag == 0 ? View.VISIBLE : View.GONE);
            llTestOne.setVisibility(flag == 1 ? View.VISIBLE : View.GONE);
            llTestTwo.setVisibility(flag == 2 ? View.VISIBLE : View.GONE);
        } else {
            if (flag == 1 || flag == 2) {
                llTestZero.setVisibility(View.VISIBLE);
                llTestOne.setVisibility(View.GONE);
                llTestTwo.setVisibility(View.GONE);
                tbTitleBar.setTitle("跑步机校准");
            } else {
                getActivity().finish();
            }
        }
    }
}
